package com.example.dboperate.utils;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.jdbc.DataSourceBuilder;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author scout.du
 * @date 2025/07/08 13:48
 **/
public class SqlExecuteUtil {

    public static List<Map<String,String>> execute(String url, String username, String password, String sql) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();

        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(mybatisConfiguration);
        DataSource dataSource = DataSourceBuilder
                .create()
                .url(url)
                .driverClassName("com.mysql.cj.jdbc.Driver")
                .username(username)
                .password(password)
                .build();
        sqlSessionFactoryBean.setDataSource(dataSource);
        SqlSessionFactory sessionFactory = sqlSessionFactoryBean.getObject();
        SqlSession sqlSession = sessionFactory.openSession();

        Connection conn = sqlSession.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();

        List<Map<String, String>> resultList = new ArrayList<>();
        while (rs.next()) {
            Map<String, String> row = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i); // 获取列名（如 "count", "app_id"）
                String columnValue = rs.getString(i); // 获取列值（转为 String）
                row.put(columnName, columnValue);
            }
            resultList.add(row);
        }
        return resultList;
    }
}
